using KlearTweet.Client.Initialization;

namespace KlearTweet.Client.Workspace
{
    public class WorkspaceController : IExceptionHandler
    {
        private readonly AccountsManager _accountsManager;
        private readonly WorkspaceView _view;

        public WorkspaceController(Application application, Shell shell, AccountsManager accountsManager)
        {
            _accountsManager = accountsManager;
            _view = new WorkspaceView();

            _view.ToggleDiagnosticPanel.Checked += (s, e) => _view.SetDiagnosticPanelVisibility(true);
            _view.ToggleDiagnosticPanel.Unchecked += (s, e) => _view.SetDiagnosticPanelVisibility(false);
            _view.ToggleDiagnosticPanel.Visibility = System.Windows.Visibility.Visible; // TODO: Hide in production?

            new Panels.NewTweetController(_view.ToggleNewTweetView, _view.NewTweetView, accountsManager);

            AddTab();
            AddTab();

            shell.Container.Child = _view;
            application.ExceptionHandler = this;
            Infrastructure.EventLogger.Verbose("KlearTweet started.");
        }


        public void Handle(System.Windows.ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
                System.Diagnostics.Debugger.Break();

            e.Handled = true;
            Infrastructure.EventLogger.Error("Unhandled Exception", e.ExceptionObject);

            var message = e.ExceptionObject is System.Net.WebException // TODO: Move to Localizer
                ? "Web request failed. Your connexion or Twitter might be down." : "Unexpected error: " + e.ExceptionObject;
            DataContainers.InfoController.Show(message);
        }


        private void AddTab()
        {
            new Tab.TabController(_accountsManager, _view.TabContainer);
        }
    }
}